package com.jwdf.uda.update;

import android.util.Log;
import com.jwdf.uda.utils.LogUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

/**
 * @author feicien (ithcheng@gmail.com)
 * @since 2016-07-05 19:25
 */
public class HttpUtils {

    public static String post(String urlStr, Map<String, Object> paramsMap) {
        HttpURLConnection uRLConnection = null;
        InputStream is = null;
        BufferedReader buffer = null;
        String result = null;
        try {
            URL url = new URL(urlStr);
            uRLConnection = (HttpURLConnection) url.openConnection();
            uRLConnection.setRequestMethod("POST");
            uRLConnection.setConnectTimeout(10000);
            uRLConnection.setReadTimeout(10000);
            uRLConnection.setDoOutput(true);

            StringBuffer params = new StringBuffer();
            // 表单参数与get形式一样
            Iterator<Map.Entry<String, Object>> iterator = paramsMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> entry = iterator.next();
                params.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            if (params.length() > 0) {
                params.deleteCharAt(params.length() - 1);
                LogUtils.i(Constants.TAG, "Http post params:"+params.toString());
                uRLConnection.getOutputStream().write(params.toString().getBytes());
            }

            is = uRLConnection.getInputStream();
            buffer = new BufferedReader(new InputStreamReader(is));
            StringBuilder strBuilder = new StringBuilder();
            String line;
            while ((line = buffer.readLine()) != null) {
                strBuilder.append(line);
            }
            result = strBuilder.toString();
        } catch (Exception e) {
            Log.e(Constants.TAG, "http post error");
        } finally {
            if (buffer != null) {
                try {
                    buffer.close();
                } catch (IOException ignored) {

                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ignored) {

                }
            }
            if (uRLConnection != null) {
                uRLConnection.disconnect();
            }
        }
        return result;
    }
}
